package com.easylinkin.linkappapi.machinery.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.easylinkin.linkappapi.config.entity.Config;
import com.easylinkin.linkappapi.config.service.ConfigService;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.deviceunit.service.DeviceUnitService;
import com.easylinkin.linkappapi.facerecognition.util.SpringContextUtil;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;

/**
 * @author xiaoyang
 * @version 1.0
 * @date 2022/08/15
 * @description
 */
public class MachineryDeviceUtil {

  private static ConfigService configService = SpringContextUtil.getBean(ConfigService.class);

  private static DeviceUnitService deviceUnitService = SpringContextUtil.getBean(DeviceUnitService.class);

  /**
   * 判断设备是否属于当前配置的设备类型
   * @param device 设备
   * @param deviceTypeKey MACHINERY_TYPE_QUIP_TSQZJ_01
   * @return
   */
  public static boolean isBelongSpecifiedDeviceType(Device device,String deviceTypeKey){
    if (null == device) {
      return false;
    }
    if (null == device || null == device.getDeviceUnit()) {
      return false;
    }
    if(null == device.getTenantId()){
      return false;
    }

    String tenantId = device.getTenantId();

    Config config = configService.getOneByKeyAndTenantId(deviceTypeKey, tenantId);
    if (config == null || StringUtils.isBlank(config.getValue())) {
      return false;
    }
    String configVal = config.getValue();
    JSONArray jsonArray = JSONUtil.parseArray(configVal);
    if (CollectionUtil.isEmpty(jsonArray)){
      return false;
    }
    List<String> unitsCodeLs = converConfigToUnitCodeList(jsonArray);
    if (CollectionUtil.isEmpty(unitsCodeLs)){
      return false;
    }
    if (unitsCodeLs.contains(device.getDeviceUnit().getCode())) {
      return true;
    }
    return false;
  }

  /**
   * @param jsonArray
   * @return
   */
  private static List<String> converConfigToUnitCodeList(JSONArray jsonArray) {
    List<String> unitTypeNameLs = jsonArray.stream().map(e -> {
      cn.hutool.json.JSONObject jsonObject = (cn.hutool.json.JSONObject) e;
      if (((cn.hutool.json.JSONObject) e).containsKey("unitTypeName")) {
        return jsonObject.getStr("unitTypeName");
      } else {
        return null;
      }
    }).collect(Collectors.toList());
    return deviceUnitService.selectDeviceUnitByDeviceTypeNames(unitTypeNameLs);
  }
}
